<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/29
 * Time: 17:20
 */

namespace app\api\controller;
use app\api\validate\Insurance;
use app\common\controller\ApiBase;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Event;
use think\facade\Filesystem;
use think\facade\Validate;
use think\Log;

class Billapi extends ApiBase
{
    private $appid = 'wxc1c600cb9953ca42';
    private $appSecrct = 'f232aec643f584202cf647caa741a32e';

    public function addInsurance(){
        $data = input('post.data');

        $val = new Insurance();
        if($val->check($data)){
            return ['code'=>0,'msg'=>$val->getError()];
        }

        if($data['isSame'] == true){
            $data['name'] = $data['ownername'];
            $data['phone'] = $data['ownerphone'];
        }

        $edata = Db::name('employee')->where('id',$data['eid'])->field('aid,name')->find();
        $data['aid'] = $edata['aid'];
        $data['update_time'] = time();

        $type = $data['type'] == 0 ? 'M' : 'D';
        $aData = Db::name('agency')->where('id',$data['aid'])->field('name,code')->find();
        $agencyCode = $aData['code'];
        $data['aname'] = $aData['name'];
        $data['billCode'] = $this->getOrderId($type.$agencyCode);
        $data['ename'] = $edata['name'];
        if($data['iid'] != ''){
            $insurance = \app\common\model\Insurance::find($data['iid']);
        }else{
            $data['create_time'] = time();
            $insurance = new \app\common\model\Insurance();
        }

        if($insurance->allowField([])->save($data)){
            return json_encode(['code'=>1,'id'=> $insurance->id]);
        }else{
            return json_encode(['code'=>0,'msg'=>'系统出错']);
        }
    }

    private function getOrderId($prefix = 'AL')
    {
        return $prefix . (strtotime(date('YmdHis', time()))) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
    }

    public function checkDeposit(){
        $data = Db::name('employee')->alias('a')->join('agency b ','a.aid = b.id')->where('a.id',input('get.uid'))->field('deposit,use_deposit')->find();

        if(!$data || empty($data['deposit'])){
            return json_encode(['code'=>0,'msg'=>'机构未设置保证金，请联系管理员']);
        }

        $num = $data['deposit'] - $data['use_deposit'];
        if($num > 10){
            $res = 0;
        }else if($num > 0 && $num <= 10){
            $res = 1;
        }else{
            $res = 2;
        }

        $insurance = Db::name('insurancetype')->where('id',input('get.iid'))->withoutField(['create_time','update_time','eid','iid','id'])->find();

        return json_encode(['code'=>1,'data'=>$res,'isData'=>!empty($insurance) ? true : false ,'insurance'=>$insurance]);
    }

    public function updateInsuranceType(){
        $data = input('post.data');

        $data['update_time'] = time();
        if($id = Db::name('insurancetype')->where('iid',$data['iid'])->value('id')){
            $insurance = \app\common\model\Insurancetype::find($id);
        }else{
            $data['create_time'] = time();
            $insurance = new \app\common\model\Insurancetype();
        }

        if($insurance->allowField([])->save($data)){
            return json_encode(['code'=>1,'iid'=> $data['iid']]);
        }else{
            return json_encode(['code'=>0,'msg'=>'系统出错']);
        }
    }

    public function getPrice(){
        $data = Db::name('insurance')->where('id',input('get.iid'))->field('ownername,plate,eid,engineCode')->find();

        if(!$data){
            return json_encode(['code'=>0,'msg'=>'未找到相关数据，请返回重新填写']);
        }

        $aid = Db::name('employee')->where('id',$data['eid'])->value('aid');

        if(!$aid){
            return json_encode(['code'=>0,'msg'=>'未找到相关业务员，请联系管理员']);
        }

        $company = Db::name('company')->where('aid',$aid)->field('name,id')->select()->toArray();

        $data['plate'] = $data['plate'] == '' ? $data['engineCode'] : $data['plate'];
        if(!$company){
            return json_encode(['code'=>0,'msg'=>'机构未设置属下保险公司，请联系管理员']);
        }


        foreach($company as $k => $v){
            $company[$k]['isPrice'] = false;
            $company[$k]['price'] = 0;
        }

        return json_encode(['code'=>1,'data'=>$data,'company'=>$company]);
    }

    public function getDetail(){
        $data = Db::name('insurance')->where('id',input('get.iid'))->field('ownername,plate,id,city,code,engineCode,style,idcard,name,phone,type')->find();
        $datatype =  Db::name('insurancetype')->where('iid',input('get.iid'))->field('commercialTime,compolsuryTime,id,iid')->find();
        $company = Db::name('company')->where('id',input('get.cid'))->field('path,name')->find();

        if(!$data || !$datatype){
            return json_encode(['code'=>0,'msg'=>'未找到相关数据，请返回重新填写']);
        }

        return json_encode(['code'=>1,'data'=>$data,'datatype'=>$datatype,'company'=>$company]);
    }

    public function getInsurance(){
        $data = Db::name('insurance')->where('id',input('get.iid'))->field('plate,register,replacement,isSec,isSame,id,seconddate,ownername,email,code,engineCode,style,idcard,name,phone,licensePath')->find();

        if(!$data){
            return json_encode(['code'=>0,'msg'=>'未找到相关数据，请返回重新填写']);
        }

        return json_encode(['code'=>1,'data'=>$data]);
    }

    public function addInsurancePhoto(){
        $data = input('post.data');

        $data['update_time'] = time();
        if($id = Db::name('insurancephoto')->where('iid',$data['iid'])->value('id')){
            $insurance = \app\common\model\Insurancephoto::find($id);
        }else{
            $data['create_time'] = time();
            $insurance = new \app\common\model\Insurancephoto();
        }

        if($insurance->allowField([])->save($data)){
            return json_encode(['code'=>1,'iid'=> $data['iid']]);
        }else{
            return json_encode(['code'=>0,'msg'=>'系统出错']);
        }
    }

    public function getInsurancePhoto(){

        $data = Db::name('insurancephoto')->where('id',input('get.iid'))->withoutField(['create_time','update_time','eid','iid','id'])->find();

        return json_encode(['code'=>1,'data'=>$data]);
    }

    public function getInsuranceInfo(){
        $data = Db::name('insurance')->where('id',input('get.iid'))->find();
        $datatype = Db::name('insurancetype')->where('id',input('get.iid'))->find();

        if(!$data){
            return json_encode(['code'=>0,'msg'=>'未找到相关数据，请返回重新填写']);
        }

        return json_encode(['code'=>1,'data'=>$data,'datatype'=>$datatype]);
    }

    public function apiInfo(){
        $imagePath = input('get.imagePath');
        require_once root_path()."extend/cloud-ocr-sdk-php-1.0.3/HWOcrClient/HWOcrClientAKSK.php";
        require_once root_path()."extend/cloud-ocr-sdk-php-1.0.3/HWOcrClient/HWOcrClientToken.php";

        $domainName = "hw02940350";
        $username = "hw02940350";
        $password = "xcm@XINGHUIWAN";
        $regionName = "cn-north-4";
        $uri = "/v1.0/ocr/vehicle-license";
        $option = [];

        $ocrServer = new \HWOcrClientToken(
            $username,
            $password,
            $domainName,
            $regionName,
            $uri
        );

        $result =  $ocrServer->RequestOcrResult($imagePath, $option);


        $result = json_decode($result,true);

        if(!isset($result['result'])){
            return json_encode(['code'=>0,'msg'=>'识别失败']);
        }else{
            return json_encode(['code'=>1,'data'=>$result['result']]);
        }
    }

    public function idInfo(){
        $imagePath = input('get.imagePath');
        require_once root_path()."extend/cloud-ocr-sdk-php-1.0.3/HWOcrClient/HWOcrClientAKSK.php";
        require_once root_path()."extend/cloud-ocr-sdk-php-1.0.3/HWOcrClient/HWOcrClientToken.php";

        $domainName = "hw02940350";
        $username = "hw02940350";
        $password = "xcm@XINGHUIWAN";
        $regionName = "cn-north-4";
        $uri = "/v1.0/ocr/id-card";
        $option = [];

        $ocrServer = new \HWOcrClientToken(
            $username,
            $password,
            $domainName,
            $regionName,
            $uri
        );

        $result =  $ocrServer->RequestOcrResult($imagePath, $option);


        $result = json_decode($result,true);

        if(!isset($result['result'])){
            return json_encode(['code'=>0,'msg'=>'识别失败']);
        }else{
            return json_encode(['code'=>1,'data'=>$result['result']]);
        }
    }
}